package com.eapi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eapi.project.common.ResultUtils;
import com.eapi.project.model.vo.statistics.BillRecordVO;
import com.eapi.project.model.vo.statistics.DateInvokeVO;
import com.eapi.project.service.InterfaceInfoService;
import com.eapi.project.service.InvokerecordService;
import com.eapi.project.service.UserService;
import com.eapi.eapicommom.model.entity.InterfaceInfo;
import com.eapi.eapicommom.model.entity.User;
import com.eapi.project.common.BaseResponse;
import com.eapi.project.model.entity.Invokerecord;
import com.eapi.project.model.vo.statistics.InterfaceInfoInvokeVO;
import com.eapi.project.model.vo.statistics.UserInvokeCount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dateStatistics")
@Slf4j
public class DateStatisticsController {
    @Resource
    private InvokerecordService invokerecordService;

    @Resource
    private UserService userService;

    @Resource
    private InterfaceInfoService interfaceInfoService;
    /**
     * 获取过去一周的接口调用情况
     * @param request
     * @return
     */
    @GetMapping("/dateStatistics")
    public BaseResponse<Map<LocalDate, List<InterfaceInfoInvokeVO>>> dateStatisticsByWeek(HttpServletRequest request) {
        Map<LocalDate, List<InterfaceInfoInvokeVO>> map = new HashMap<>();
        List<DateInvokeVO> dateInvokeVOS = invokerecordService.dateStatistics();
        LocalDate now = LocalDate.now();
        List<LocalDate> localDates = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            localDates.add(now.minusDays(i));
        }
        // 向map中添加数据库中可查出来的数据
        for (int i = 0; i < dateInvokeVOS.size(); i++) {
            DateInvokeVO dateInvokeVO = dateInvokeVOS.get(i);
            LocalDate invokeDate = dateInvokeVO.getInvokeDate();
            Integer invokeNum = dateInvokeVO.getInvokeNum();
            String interfaceInfoName = dateInvokeVO.getInterfaceInfoName();
            InterfaceInfoInvokeVO interfaceInfoInvokeVO = new InterfaceInfoInvokeVO(invokeNum,interfaceInfoName);
            if (!map.containsKey(invokeDate)){
                map.put(invokeDate, new ArrayList<>());
            }
            map.get(invokeDate).add(interfaceInfoInvokeVO);
        }

        // 向数据库中插入一周内某天一个接口都没有调用过的数据
        for (int i = 0; i < localDates.size(); i++) {
            if(!map.containsKey(localDates.get(i))){
                map.put(localDates.get(i), new ArrayList<>());
            }
        }

        // 查询所有存在的接口
        List<InterfaceInfo> list = interfaceInfoService.list();
        // 向map中插入未调用过的数据
        map.forEach((localDate, interfaceInfoInvokeVOS) -> {
            for (InterfaceInfo info : list) {
                String interfaceInfoName = info.getName();
                boolean found = false;
                for (InterfaceInfoInvokeVO existingInvokeVO : interfaceInfoInvokeVOS) {
                    if (existingInvokeVO.getInterfaceInfoName().equals(interfaceInfoName)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    InterfaceInfoInvokeVO missingInvokeVO = new InterfaceInfoInvokeVO(0, interfaceInfoName);
                    interfaceInfoInvokeVOS.add(missingInvokeVO);
                }
            }
        });
        return ResultUtils.success(map);
    }

    /**
     * 用户调用情况统计
     */
    @GetMapping("/billrecord")
    public BaseResponse<List<BillRecordVO>> billRecord(HttpServletRequest request) {
        // 获取用户id
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        // 根据用户id查询调用记录
        LambdaQueryWrapper<Invokerecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Invokerecord::getUserId,userId);
        queryWrapper.orderByDesc(Invokerecord::getCreatetime);
        List<Invokerecord> invokerecords = invokerecordService.list(queryWrapper);
        List<BillRecordVO> billRecordVOS = new ArrayList<>();

        for (Invokerecord invokerecord : invokerecords) {
            BillRecordVO billRecordVO = new BillRecordVO();
            BeanUtils.copyProperties(invokerecord,billRecordVO);
            billRecordVOS.add(billRecordVO);
        }
        return ResultUtils.success(billRecordVOS);
    }

    @GetMapping("/billrecord/total")
    public BaseResponse<Long> invokerecordTotal(HttpServletRequest request) {
        // 获取用户id
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        // 根据用户id查询调用记录
        QueryWrapper<Invokerecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        Long totalCost = invokerecordService.getTotalCost(userId);
        if (totalCost == null){
            return ResultUtils.success(0L);
        }
        return ResultUtils.success(totalCost);
    }

    @GetMapping("/invokeCountStatistics")
    public BaseResponse<List<UserInvokeCount>> getCountStatistics(HttpServletRequest request){

        User loginUser = userService.getLoginUser(request);
        List<UserInvokeCount> userInvokeCounts = invokerecordService.getMostLikeInterface(loginUser.getId());
        return ResultUtils.success(userInvokeCounts);
    }
}
